/**
Zeke Elder - zbe@andrew.cmu.edu
Amal Chemmany - achemman@andrew.cmu.edu
Nishant Kumar - nkumar1@andrew.cmu.edu
15-637
4/2/2012
 **/

package edu.cmu.fithub.actions;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import edu.cmu.fithub.controller.Action;
import edu.cmu.fithub.db.DBHelper;
import edu.cmu.fithub.db.bean.Group;
import edu.cmu.fithub.db.bean.GroupMembershipNotification;
import edu.cmu.fithub.db.bean.User;

public class InviteMemberAction extends Action {

	public InviteMemberAction() {
	}

	public String getName() {
		return "inviteMember.do";
	}

	public String perform(HttpServletRequest request) {

		List<String> errors = new ArrayList<String>();
		request.setAttribute("errors", errors);
		String groupId = request.getParameter("groupId");

		try {
			User user = (User) request.getSession().getAttribute("user");
			String userId = request.getParameter("id");
			Session dbSession = DBHelper.getSessionFactory().openSession();
			GroupMembershipNotification notification = new GroupMembershipNotification();

			List<Group> groupList = dbSession.createCriteria(Group.class)
					.add(Restrictions.eq("groupId", Integer.parseInt(groupId)))
					.add(Restrictions.eq("adminId", user.getUserId())).list();
			List<User> userList = dbSession.createCriteria(User.class)
					.add(Restrictions.eq("userId", Integer.parseInt(userId)))
					.list();
			if (groupList.size() != 0 && userList.size() != 0) {

				List<GroupMembershipNotification> notifyList = dbSession
						.createCriteria(GroupMembershipNotification.class)
						.add(Restrictions.eq("userId", Integer.parseInt(userId)))
						.add(Restrictions.eq("group.groupId", groupList.get(0)
								.getGroupId())).list();
				if(notifyList.size() > 0) {
					// user already invited
					errors.add("User already invited!!!");
					return "error.jsp";
				}

				notification.setGroup(groupList.get(0));
				notification.setUserId(userList.get(0).getUserId());
				dbSession.beginTransaction();
				dbSession.save(notification);
				dbSession.getTransaction().commit();
			}
		} catch (Exception e) {
			errors.add(e.toString());
			return "error.jsp";
		}

		// return "invite.jsp";
		return "showGroupHome.do?groupId=" + groupId;
	}
}
